<template>
  <div class="bodyMap">
    <div style=" background-color: #94C9FF;font-weight: bold;padding: 0.2rem" @click="backIndex()">
      <i class="el-icon-back"/>回到主页
    </div>
    <div style="display: flex;justify-content: center;align-items: center;background-color: #94C9FF;padding-bottom: 0.5rem">
      <span class="text">降雨预报</span>
    </div>
    <div id="cityChart" class="cityChart"></div>
    <div class="citySel">
      <el-select v-model="cityName" size="mini" @change="mapClick">
        <el-option :value="item.name" :key="item.id" v-for="item in cityInformation"/>
      </el-select>
    </div>
    <div class="mapInfo" v-if="mapInfoShow">
      <div style="margin: 0.2rem 0.3rem; color: #ffffff; font-size: 0.4rem">
        {{ mapInfoObj.name }}
      </div>
      <div style="display: flex;align-items: center;justify-content: space-around">
        <div class="textStyle">
          <div>当日气温:</div>
          <div style="margin-left: 0.1rem">{{ mapInfoObj.temp }}℃</div>
        </div>
        <div class="textStyle">
          <div>降雨量:</div>
          <div style="margin-left: 0.1rem">{{ mapInfoObj.precip }}mm</div>
        </div>
        <div class="textStyle">
          <div>风速:</div>
          <div style="margin-left: 0.1rem">{{ mapInfoObj.windScale }}级</div>
        </div>
        <div class="textStyle">
          <div>风向:</div>
          <div style="margin-left: 0.1rem">{{ mapInfoObj.windDir }}</div>
        </div>
        <div class="textStyle">
          <div>湿度:</div>
          <div style="margin-left: 0.2rem">{{ mapInfoObj.humidity }}%</div>
        </div>
      </div>
    </div>
    <div class="precipChart">
      <div ref="weatherForecast" class="weatherForecast"></div>
      <div class="chartText">
        <span>聊城市7日气温及降水量变化图</span>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import 'lib-flexible'
import liaoChengJson from "@/utils/city-infoJson/liaoCheng.json";
import "echarts-gl";
import { rgb } from "chalk";
import {weatherInfo, weatherInfoForSeenDay} from "@/api/cityInfo";
import { formatDate, formatDateMonth } from "../utils";
import AMapLoader from "@amap/amap-jsapi-loader";
import {cityInformation} from "@/utils/city-information";

export default {
  name: "wxWeatherInfo",
  data() {
    return {
      cityChart: "",
      cityInformation: [
        { name: "冠县", id: "101121702" },
        { name: "阳谷县", id: "101121703" },
        { name: "高唐县", id: "101121704" },
        { name: "茌平区", id: "101121705" },
        { name: "东阿县", id: "101121706" },
        { name: "临清市", id: "101121707" },
        { name: "莘县", id: "101121709" },
        { name: "东昌府区", id: "101121708" },
      ],
      mapInfoObj: {},
      mapInfoShow: true,
      companyList:[],
      futureWeatherFifteenList:[],
      cityName:'东昌府区',
      myChart:null,
      echartsOption: {},
      map: null,
      AMap: null,
      loading:false,
      companyTqList:[],
      listJs:[],
      polygon:[],
    };
  },
  mounted() {
    this.getCityWeatherToday();
    this.getFutureWeatherForFifteen();
    // this.renderMap();
    this.info();
    this.getWeather()
  },
  methods: {
    formatDate,
    //获取实时天气信息
    async getWeather() {
      this.loading = true;
      this.companyTqList = [];
      //清空降水点坐标
      this.emptyingPointsJs();
      cityInformation.map(async (item) => {
        let resJson = await weatherInfo({
          location: item.id,
          lang: "zh",
          cityName: item.name,
        });
        let res = await JSON.parse(resJson.data);
        this.companyTqList.push({
          ...item,
          ...res.now,
        });
        if (cityInformation.length <= this.companyTqList.length) {
          this.loading = false;
          await this.setMarkerJs();
        }
      });
      // this.companyTqList = csDataLHYLL
      await this.setMarkerJs();
    },
    //渲染降水信息
    setMarkerJs() {
      this.listJs = [];
      this.companyTqList.map(async (item) => {
        let marker = new AMap.Marker({
          content: `<div><i style="color: #393eff;font-size: 18px" class="qi-309"/><div style="font-size: 12px">${item.precip}mm/h</div></div>`,
          map: this.map,
          position: new AMap.LngLat(item.lon, item.lat),
          offset: new AMap.Pixel(-50, 5),
        });
        this.listJs.push(marker);
      });
    },
    //清空降水点坐标
    emptyingPointsJs() {
      if (this.listJs.length != 0) {
        this.listJs.forEach((e) => {
          e.setMap(null);
        });
        this.map.remove(this.listJs);
      }
      this.listJs = [];
    },
    async getCityWeatherToday() {
      this.cityInformation.map(async (item) => {
        let resJson = await weatherInfo({
          location: item.id,
          lang: "zh",
          cityName: item.name,
        });
        let res = await JSON.parse(resJson.data);
        this.companyList.push({
          ...item,
          ...res.now,
        });
        if (this.cityInformation.length == this.companyList.length) {
          this.mapClick("东昌府区");
        }
      });
    },
    //初始化地图
    info() {
      let that = this;
      let map = null;
      window._AMapSecurityConfig = {
        securityJsCode: "41e17bd194dc80120ab5e431f6e5264e",
      };
      AMapLoader.load({
        key: "e9f5683c5fe13b606dc1179f1e503062", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.MapType",
          "AMap.Geolocation",
          "AMap.DistrictSearch",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then(async (AMap) => {
          let obj = {
            center: [114.890829, 36.911746],
            resizeEnable: true,
            showLabel: true,
            viewMode: "3D",
            expandZoomRange: true,
            zoom: 8,
          };
          // if (that.radio != 3){
          //   obj.mask = mask
          //   obj.zoom = 9.8
          //   obj.zooms = [9,13]
          // }
          map = new AMap.Map("cityChart", obj);

          // 地图添加各种控件
          // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
          map.addControl(new AMap.ToolBar());
          // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
          map.addControl(new AMap.MapType());
          // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
          map.addControl(new AMap.Scale());
          // 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
          // map.addControl(new AMap.Geolocation())
          //获取边界坐标点
          AMap.plugin("AMap.DistrictSearch", function () {
            let districtSearch = new AMap.DistrictSearch({
              // 关键字对应的行政区级别，共有5种级别
              level: "province",
              //  是否显示下级行政区级数，1表示返回下一级行政区
              subdistrict: 0,
              // 返回行政区边界坐标点
              extensions: "all",
            });

            districtSearch.search("聊城", (status, result) => {
              // 查询成功时，result即为对应的行政区信息
              let bounds = result.districtList[0].boundaries;
              if (bounds) {
                for (let i = 0, l = bounds.length; i < l; i++) {
                  //生成行政区划polygon
                  let polygon = new AMap.Polygon({
                    map: map, // 指定地图对象
                    strokeWeight: 2, // 轮廓线宽度
                    path: bounds[i], //轮廓线的节点坐标数组
                    fillOpacity: 0.6, //透明度
                    fillColor: "", //填充颜色
                    strokeColor: "#3a8670", //线条颜色
                  });
                  // polygon.on("click", (value) => {
                  //   that.getTwoHoursWeather(value.lnglat.lat, value.lnglat.lng);
                  // });
                }
              }
            });
          });
          map.setCenter([115.9984837, 36.4551603]);
          that.map = map;
          that.AMap = AMap;
          // map.on("click", (value) => {
          //   that.getTwoHoursWeather(value.lnglat.lat, value.lnglat.lng);
          // });
        })
        .catch((e) => {
          console.log("错误", e);
        });
    },
    renderMap() {
      let that = this;
      const echartsConDom = document.getElementById("cityChart");
      this.myChart = echarts.init(echartsConDom); // 初始化
      echarts.registerMap("liaochengMap", liaoChengJson);
      this.echartsOption = {
        tooltip: {
          show: false,
        },
        series: [
          {
            type: "map3D",
            name:'mapStyle',
            map: "liaochengMap",
            itemStyle: {
              color: "#529dff", // 背景颜色
              opacity: 1,
              borderWidth: 0.2,
              borderColor: "#cccccc",
            },
            boxWidth:90,
            boxHeight:80,
            top: 0,
            left: 20,
            width: "100%",
            height: "100%",
            regionHeight: 3,
            shading: "color",
            label: {
              show: true,
              color: "#ffffff",
              fontSize: 12,
              fontWeight: 500,
              opacity: 1,
            },
            viewControl: {
              // autoRotate: true,
              rotateSensitivity: 0,
              distance: 60,
              minDistance: 130,
              maxDistance: 130,
            },
            emphasis: {
              itemStyle: {
                color: "rgb(241,13,13)",
              },
            },
            data: [
              { name: "阳谷县", itemStyle: { color: "#359fe4" } },
              { name: "莘县", itemStyle: { color: "#2184ca" } },
              { name: "东昌府区", itemStyle: { color: "#58aef0" } },
              { name: "冠县", itemStyle: { color: "#568bc5" } },
              { name: "东阿县", itemStyle: { color: "#78caff" } },
              { name: "茌平区", itemStyle: { color: "#5199ef" } },
              { name: "高唐县", itemStyle: { color: "rgba(102,168,250)" } },
              { name: "临清市", itemStyle: { color: "#5199ef" } },
            ],
          },
        ],
      }
      this.myChart.setOption(this.echartsOption);
      this.myChart.on("click", function (value) {
        that.mapClick(value.name);
      });
      // myChart.on("tap", function (value) {
      //   that.mapClick(value.name);
      //   alert(2)
      // });
      // myChart.on("touchend", function (value) {
      //   that.mapClick(value.name);
      //   alert(3)
      // });
    },
    mapClick(name) {
      this.companyList.forEach((item) => {
        if (item.name == name) {
          this.mapInfoObj = item;
          this.mapInfoShow = true;
          this.selectMapLabel(name)
        }
      });
    },
    selectMapLabel(label){
      if (this.polygon.length > 0){
        this.map.remove(this.polygon)
      }
      let that = this
      this.AMap.plugin('AMap.DistrictSearch', function () {
        let districtSearch = new AMap.DistrictSearch({
          // 关键字对应的行政区级别，共有5种级别
          level: "district",
          //  是否显示下级行政区级数，1表示返回下一级行政区
          subdistrict: 1,
          // 返回行政区边界坐标点
          extensions: "all",
        });
        // that.qdMapTitle.forEach(async item => {
        districtSearch.search(label, (status, result) => {
          // 查询成功时，result即为对应的行政区信息
          console.log(result)
          let bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (let i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              let polygon = new AMap.Polygon({
                map:that.map,
                strokeWeight: 2, // 轮廓线宽度
                path: bounds[i], //轮廓线的节点坐标数组
                fillOpacity: 0.6, //透明度
                fillColor: 'rgba(177,215,250,0.1)', //填充颜色
                strokeColor: "rgba(153,203,252,0.1)", //线条颜色
              });
              that.polygon.push(polygon)
            }
          }
        });
        // })
      })
      // this.map.setZoomAndCenter(10,[this.cityMenuList[label].lon,this.cityMenuList[label].lat],true,1000)
    },
    async getFutureWeatherForFifteen() {
      let resJson = await weatherInfoForSeenDay({
        location: "101121701",
        lang: "zh",
        cityName: "聊城",
      });
      let res = JSON.parse(resJson.data);
      this.futureWeatherFifteenList = res.daily;
      await this.chartInit();
    },
    chartInit() {
      let date = [];
      let jsDate = [];
      let qwDate = [];
      this.futureWeatherFifteenList.forEach((item) => {
        date.push(formatDateMonth(item.fxDate));
        jsDate.push(Number(item.precip));
        qwDate.push(Number(item.tempMin));
      });
      const chartItem = this.$refs.weatherForecast;
      let myChart = echarts.init(chartItem,null,{
        renderer:'canvas'
      });
      let option = {
        grid: [
          {
            top: "15%",
            bottom: "10%",
            left: "15%",
            right: "10%",
          },
        ],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        toolbox: {
          feature: {
            dataView: { show: false, readOnly: false },
            magicType: { show: false, type: ["line", "bar"] },
            // restore: { show: true },
            saveAsImage: { show: false },
          },
        },
        xAxis: [
          {
            type: "category",
            data: date,
            axisPointer: {
              type: "shadow",
            },
            axisLabel: {
              color: "#88a4cb", // 将X轴单位颜色改为#15599D
            },
            axisLine: {
              lineStyle: {
                color: "#88a4cb", // 将X轴线颜色改为#88a4cb
              },
            },
            axisTick: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "气温",
            // min: 0,
            // interval: 5,
            nameTextStyle: {
              color: "#fff", // 将Y轴标识颜色改为白色
            },
            axisLabel: {
              formatter: "{value} °C",
              color: "#88a4cb", // 将Y轴单位颜色改为#15599D
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: "#15599D",
              },
            },
          },
          {
            type: "value",
            name: "降水量",
            nameTextStyle: {
              color: "#fff", // 将Y轴标识颜色改为白色
            },
            min: 0,
            interval: 50,
            axisLabel: {
              formatter: "{value} ml",
              color: "#88a4cb", // 将Y轴单位颜色改为#15599D
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
                color: "#15599D",
              },
            },
          },
        ],
        series: [
          {
            name: "气温",
            type: "line",
            yAxisIndex: 0, // 左侧Y轴
            smooth: true, // 使折线圆润
            // symbol: "none", // 隐藏数据点标记
            tooltip: {
              valueFormatter: function (value, dataIndex) {
                return value + " °C";
              },
            },
            itemStyle: {
              color: "#1E56FF", // 设置折线颜色
            },
            data: qwDate,
          },
          {
            name: "降水量",
            type: "bar",
            yAxisIndex: 1, // 右侧Y轴
            tooltip: {
              valueFormatter: function (value) {
                return value + " ml";
              },
            },
            itemStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "#21DAE9", // 顶部颜色
                  },
                  {
                    offset: 1,
                    color: "#0D315B", // 底部颜色
                  },
                ],
              },
              barBorderRadius: [10, 10, 0, 0], // 圆柱顶端为半圆形
            },
            data: jsDate,
          },
        ],
      };
      option && myChart.setOption(option);
    },
    backIndex(){
      this.$router.push({
        path:'/wxIndex'
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.bodyMap{
  background-color: #60AEFF;
  height: 100vh;
  position: relative;
}
.text{
  margin-top: 20px;
  font-size: 16px;
}
.cityChart{
  width: 100%;
  height: 350px;
  touch-action: none !important;
}
.citySel{
  position: absolute;
  z-index: 1000;
  top: 100px;
  left: 10px;
  box-shadow: 0 0 4px 1px rgba(0, 0, 0, 0.4);
  border-radius: 10px;
}
::v-deep .el-input__inner{
  width: 100px;
  background-color: #f6f6f6;
  border: 0px solid #ffffff;
}
.mapInfo {
  padding: 5px;
  background-color: #99CBFC;
  z-index: 100;
  .textStyle {
    display: flex;
    flex-direction: row;
    align-items: center;
    color: #F4FCFB;
  }
}
.precipChart{
  background-color: #FFFFFF;
  overflow-x: auto;
}
.weatherForecast{
  width: 150%;
  height: 200px;
}
.chartText{
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px;
  color: #7094B7;
}
</style>
